package org.itboys.seller.service;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.itboys.commons.utils.cookie.CookieUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.seller.constant.SellerConstants;
import org.itboys.seller.constant.SellerCookieConstant;
import org.itboys.seller.constant.SellerSessionConstant;
import org.itboys.seller.entity.SellerUser;
import org.itboys.seller.utils.SellerSessionHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商家登陆账号
 * @author weisky
 *
 */
@Service
public class SellerUserService extends BaseService< SellerUser, Long>{
	
	private static final long serialVersionUID = 1L;

	@Resource(name = "sellerDS")
	private MongoDataSource ds;
	
	@Autowired
	private ResourceHolder resourceHolder;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<SellerUser> getEntityClass() {
		return SellerUser.class;
	}
	
	/**
	 * 修改或保存
	 * @param sellerUser
	 * @param logos
	 * @return 0:系统错误  1：成功  2：用户名已存在
	 */
	public int insert(SellerUser sellerUser, MultipartFile logos){
		try{
			Long sellerId = SellerSessionHolder.getSellerId();
			if(sellerId != null ){//设置账号所属的商家
				sellerUser.setSellerId(sellerId);
			}
			sellerUser.setUserName(sellerUser.getUserName().toLowerCase());//用户名转小写
			sellerUser.setPassword(Digests.md5(sellerUser.getPassword()));//将密码转换成MD5加密
			
			if(sellerUser.getId() == 0){//新增时  判断该账号是否已存在
				boolean isexist = exists("userName", sellerUser.getUserName());
				if(isexist){//该用户名已存在
					return 2;
				}
			}
			
			String logo = null;
			if(logos != null && !logos.isEmpty()){
				logo = FileUtils.saveFile(logos.getInputStream(), resourceHolder.getStringValue("fileUploadPath"), logos.getOriginalFilename(), logos.getContentType());
			}
			
			if(sellerUser.getId() != 0){//修改
				SellerUser sellerUser2 = getById(sellerUser.getId());
				if(StringUtils.isNotBlank(logo)){//设置头像
					sellerUser.setLogo(logo);
				}else{
					sellerUser.setLogo(sellerUser2.getLogo());
				}
				if(StringUtils.equals(Digests.md5(""), sellerUser.getPassword())){//密码为空
					sellerUser.setPassword(sellerUser2.getPassword());//若是密码为空  就设置成原来的密码
				}
				update(sellerUser);
			}else{//新增
				sellerUser.setLogo(logo);
				save(sellerUser);
			}
			return 1;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.insert error", e);
			return 0;//失败
		}
	}
	
	/**
	 * 修改商家账号的状态
	 * @param sellerUserId
	 * @param state 0：冻结  1：开通
	 * @return
	 */
	public boolean updateState(Long sellerUserId, int state){
		try{
			update(sellerUserId, "state", state);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.updateState error", e);
			return false;
		}
	}
	
	/**
	 * 登陆
	 * @param userName
	 * @param password
	 * @param response
	 * @return
	 */
	public int login(String userName, String password, HttpServletResponse response){
		try{
			
			SellerUser sellerUser = getByField("userName", userName);
			if(sellerUser == null){
				return -1;//用户不存在
			}
			if(SellerConstants.ACCOUNT_FROZEN == sellerUser.getState()){//账号被冻结
				return -3;
			}
			if(!StringUtils.equals(sellerUser.getPassword(), Digests.md5(password))){
				logger.warn("商家账号登陆异常：账号名："+userName+"，登陆密码："+password+"，密码不匹配");
				return -2;//密码不正确
			}
			sellerUser.setLoginTime(System.currentTimeMillis());//登陆时间
			sellerUser.setLoginIp(SellerSessionHolder.getLoginIp());//登陆IP
			update(sellerUser);//修改登陆人的登陆时间和IP
			
			CookieUtils.addCookie(response, SellerCookieConstant.COOKIE_USER_NAME, userName, 864000);
			ServletContextHolder.getSession().setAttribute(SellerSessionConstant.SESSION_USER_ID, sellerUser.getId());
			ServletContextHolder.getSession().setAttribute(SellerSessionConstant.SESSION_SELLER_ID, sellerUser.getSellerId());
			ServletContextHolder.getSession().setAttribute(SellerSessionConstant.SESSION_SELLER_ID2, sellerUser.getSellerId());
			ServletContextHolder.getSession().setAttribute(SellerSessionConstant.SESSION_SELLER_USER_NAME, sellerUser.getUserName());
			ServletContextHolder.getSession().setMaxInactiveInterval(Integer.valueOf(resourceHolder.getStringValue("sessionMaxInactiveInterval")));//设置session有效时间
			return SellerConstants.ACTION_SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.login error", e);
			return SellerConstants.ACTION_FAIL;//操作失败
		}
	}

	/**
	 * 删除
	 * @param sellerUserId
	 * @return
	 */
	public boolean dele(Long sellerUserId){
		try{
			super.delete(sellerUserId);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.dele error", e);
			return false;
		}
	}
	
	/**
	 * 修改商家账号所拥有的菜单
	 * @param userId
	 * @param menuIds
	 * @return
	 */
	public boolean updateUserMenuIds(Long userId, List<Long> menuIds){
		try{
			super.update(userId, "menuIds", menuIds);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.updateUserMenuIds error", e);
			return false;
		}
	}
	
	/**
	 * 修改商家账号对用的角色
	 * @param userId
	 * @param roleIds
	 * @return
	 */
	public boolean updateUserRoleIds(Long userId, List<Long> roleIds){
		try{
			super.update(userId, "roleIds", roleIds);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("SellerUserService.updateUserMenuIds error", e);
			return false;
		}
	}
	
}
